﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HandyControl.Controls;
using HandyControl.Data;
using IoTClient.Enums;
using LiveCharts;
using Microsoft.Extensions.DependencyInjection;
using MQTTnet;
using MQTTnet.Client;
using NAudio.Wave;
using QControlCenter.Pages;
using QModels;
using QServices;
using QServices.Services;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Media;
using System.Numerics;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace QControlCenter.ViewModel
{
	public partial class LsdViewModel : ObservableObject
	{
		private static string[] AreaList = new string[] { "A", "B", "C", "D", "E" };
		private static string[] WeekChinese = new string[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
		public static string[] ModelTextArray = new string[] { "手动模式", "春秋模式", "夏季模式", "冬季模式" };
		public static Dictionary<CarStatus, string> CarSatusDic = new Dictionary<CarStatus, string>()
		{
			[CarStatus.None] = AGVCarStatus.DaiJiZhong,
			[CarStatus.DaiJi] = AGVCarStatus.DaiJiZhong,
			[CarStatus.WeiLiao] = AGVCarStatus.WeiLiaoZhong,
			[CarStatus.Trouble] = AGVCarStatus.QianFangGuZhang,
			[CarStatus.Charging] = AGVCarStatus.ChongDianZhong
		};

		[ObservableProperty]
		private string? selectModelTextA;
		[ObservableProperty]
		private string? selectModelTextB;
		[ObservableProperty]
		private string? selectModelTextC;
		[ObservableProperty]
		private string? selectModelTextD;
		[ObservableProperty]
		private string? selectModelTextE;


		[ObservableProperty]
		private int sensor_temperature_Use;
		[ObservableProperty]
		private int sensor_temperature_All;
		[ObservableProperty]
		private int sensor_humidity_Use;
		[ObservableProperty]
		private int sensor_humidity_All;

		[ObservableProperty]
		private int sensor_co2_Use;
		[ObservableProperty]
		private int sensor_co2_All;

		[ObservableProperty]
		private int shuiLian_Use;
		[ObservableProperty]
		private int shuiLian_All;
		[ObservableProperty]
		private int shuiLian_Error;


		[ObservableProperty]
		private int daoLiuBan_Use;
		[ObservableProperty]
		private int daoLiuBan_All;
		[ObservableProperty]
		private int daoLiuBan_Error;


		[ObservableProperty]
		private int dianDongBaiYe_Use;
		[ObservableProperty]
		private int dianDongBaiYe_All;
		[ObservableProperty]
		private int dianDongBaiYe_Error;


		[ObservableProperty]
		private int daFengJiZu_Use;
		[ObservableProperty]
		private int daFengJiZu_All;
		[ObservableProperty]
		private int daFengJiZu_Error;


		[ObservableProperty]
		private int cePaiFeng_Use;
		[ObservableProperty]
		private int cePaiFeng_All;
		[ObservableProperty]
		private int cePaiFeng_Error;


		[ObservableProperty]
		private int xinFeng_Use;
		[ObservableProperty]
		private int xinFeng_All;
		[ObservableProperty]
		private int xinFeng_Error;



		#region 鸽笼监控

		/// <summary>
		/// 鸽笼管理
		/// </summary>
		[ObservableProperty]
		private int geLongGuanLi;

		/// <summary>
		/// 空置鸽笼
		/// </summary>
		[ObservableProperty]
		private int kongZhigeLong;

		/// <summary>
		/// 查蛋
		/// </summary>
		[ObservableProperty]
		private int chaDan;

		/// <summary>
		/// 照蛋
		/// </summary>
		[ObservableProperty]
		private int zhaoDan;

		/// <summary>
		/// 查雏
		/// </summary>
		[ObservableProperty]
		private int chaChu;

		/// <summary>
		/// 出栏
		/// </summary>
		[ObservableProperty]
		private int chuLan;

		/// <summary>
		/// 淘汰
		/// </summary>
		[ObservableProperty]
		private int taoTai;

		/// <summary>
		/// 补栏
		/// </summary>
		[ObservableProperty]
		private int buLan;

		/// <summary>
		/// 调并
		/// </summary>
		[ObservableProperty]
		private int tiaoBing;

		/// <summary>
		/// 健康检查
		/// </summary>
		[ObservableProperty]
		private int jianKangJianCha;

		#endregion

		#region AGV智能机器人监控
		[ObservableProperty]
		private DosingScheduleViewModel firstDosingSchedule;
		[ObservableProperty]
		private DosingScheduleViewModel secondDosingSchedule;
		[ObservableProperty]
		private DosingScheduleViewModel thirdDosingSchedule;
		[ObservableProperty]
		private DosingScheduleViewModel fourDosingSchedule;
		[ObservableProperty]
		private DosingScheduleViewModel fiveDosingSchedule;

		#endregion


		#region 环控设备运行监控
		[ObservableProperty]
		private decimal temperature_A;
		[ObservableProperty]
		private decimal temperature_B;
		[ObservableProperty]
		private decimal temperature_C;
		[ObservableProperty]
		private decimal temperature_D;
		[ObservableProperty]
		private decimal temperature_E;

		[ObservableProperty]
		private string areaModel_A;
		[ObservableProperty]
		private string areaModel_B;
		[ObservableProperty]
		private string areaModel_C;
		[ObservableProperty]
		private string areaModel_D;
		[ObservableProperty]
		private string areaModel_E;

		[ObservableProperty]
		private string dangWei_A;
		[ObservableProperty]
		private string dangWei_B;
		[ObservableProperty]
		private string dangWei_C;
		[ObservableProperty]
		private string dangWei_D;
		[ObservableProperty]
		private string dangWei_E;

		[ObservableProperty]
		private decimal auto_Temperature_A;
		[ObservableProperty]
		private decimal auto_Temperature_B;
		[ObservableProperty]
		private decimal auto_Temperature_C;
		[ObservableProperty]
		private decimal auto_Temperature_D;
		[ObservableProperty]
		private decimal auto_Temperature_E;

		[ObservableProperty]
		private string runTime_A;
		[ObservableProperty]
		private string runTime_B;
		[ObservableProperty]
		private string runTime_C;
		[ObservableProperty]
		private string runTime_D;
		[ObservableProperty]
		private string runTime_E;

		[ObservableProperty]
		private decimal? upperTemperature_ShuiLian;
		[ObservableProperty]
		private decimal? startTime_ShuiLian;
		[ObservableProperty]
		private decimal? endTime_ShuiLian;

		#endregion


		/// <summary>
		/// 报警温度
		/// </summary>
		[ObservableProperty]
		private decimal alarmTemperature;

		public ChartValues<decimal> TemperatureList { get; set; } = new ChartValues<decimal>();
		public ChartValues<decimal> HumidityList { get; set; } = new ChartValues<decimal>();
		public ChartValues<decimal> Co2List { get; set; } = new ChartValues<decimal>();

		[ObservableProperty]
		private string currentDate;
		[ObservableProperty]
		private string currentTime;
		[ObservableProperty]
		private string currentWeek;
		[ObservableProperty]
		private decimal currentTemperature;

		[ObservableProperty]
		private string showAlarmGif;//Visible  Hidden

		public static IConnectionFactory? ConnectionFactory { get; set; }
		public static IModel? RabbitMQChannel { get; set; }
		public static IConnection? RabbitMQConection { get; set; }
		public static EventingBasicConsumer? RabbitMQConsumer { get; set; }


		public static IMqttClient? m_mqttclient { get; set; } = null;
		public static Dictionary<string, DateTime> TongXinTimeDic { get; set; } = new Dictionary<string, DateTime>();

		public async void InitRabbitMQ()
		{
			ConnectionFactory = new ConnectionFactory { HostName = AppRuntime.Rabbitmq_ip, Port = AppRuntime.Rabbitmq_port.Value, Password = AppRuntime.Rabbitmq_pwd, UserName = AppRuntime.Rabbitmq_user };
			RabbitMQConection = ConnectionFactory.CreateConnection();
			RabbitMQChannel = RabbitMQConection.CreateModel();
			RabbitMQConsumer = new EventingBasicConsumer(RabbitMQChannel);
			RabbitMQConsumer.Received += RabbitHandler;
			RabbitMQChannel.BasicConsume(queue: "pigeonWarning",
								 autoAck: true,
								 consumer: RabbitMQConsumer);


			#region 小车电量
			var options = new MqttClientOptionsBuilder()
				.WithTcpServer(AppRuntime.Rabbitmq_ip, 1883)
				.WithCredentials(AppRuntime.Rabbitmq_user, AppRuntime.Rabbitmq_pwd)
				.WithKeepAlivePeriod(TimeSpan.FromSeconds(10))
				.Build();

			var factory = new MqttFactory();
			m_mqttclient = factory.CreateMqttClient();
			m_mqttclient.ApplicationMessageReceivedAsync += M_mqttclient_ApplicationMessageReceivedAsync;
			await m_mqttclient.ConnectAsync(options);

			await m_mqttclient.SubscribeAsync("CarElectricQty");
			await m_mqttclient.SubscribeAsync("UpdateCarStatus");

			#endregion




		}

		private Task M_mqttclient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
		{

			var msg = Encoding.UTF8.GetString(arg.ApplicationMessage.PayloadSegment);
			var topic = arg.ApplicationMessage.Topic;
			if (topic == null) return Task.CompletedTask;
			if (topic == "CarElectricQty")
			{
				var carEle = JsonSerializer.Deserialize<CarElectricQty>(msg);
				if (carEle != null)
				{
					var qty = (int)(carEle.Qty / 200 * 100);
					if (carEle.CarNumber == "A" || carEle.CarNumber == "1")
					{
						firstDosingSchedule.Electricity = qty;
						firstDosingSchedule.CarStatus = CarSatusDic[(CarStatus)carEle.CarStatus];
						firstDosingSchedule.TongXinPath =carEle.TongXin? AGVCarStatus.TongXinOK:AGVCarStatus.TongXinError;
						

					}
					if (carEle.CarNumber == "B" || carEle.CarNumber == "2")
					{
						secondDosingSchedule.Electricity = qty;
						secondDosingSchedule.CarStatus = CarSatusDic[(CarStatus)carEle.CarStatus];
						secondDosingSchedule.TongXinPath = carEle.TongXin ? AGVCarStatus.TongXinOK : AGVCarStatus.TongXinError;
					}
					if (carEle.CarNumber == "C" || carEle.CarNumber == "3")
					{
						thirdDosingSchedule.Electricity = qty;
						thirdDosingSchedule.CarStatus = CarSatusDic[(CarStatus)carEle.CarStatus];
						thirdDosingSchedule.TongXinPath = carEle.TongXin ? AGVCarStatus.TongXinOK : AGVCarStatus.TongXinError;
					}
					if (carEle.CarNumber == "D" || carEle.CarNumber == "4")
					{
						fourDosingSchedule.Electricity = qty;
						fourDosingSchedule.CarStatus = CarSatusDic[(CarStatus)carEle.CarStatus];
						fourDosingSchedule.TongXinPath = carEle.TongXin ? AGVCarStatus.TongXinOK : AGVCarStatus.TongXinError;
					}
					if (carEle.CarNumber == "E" || carEle.CarNumber == "5")
					{
						fiveDosingSchedule.Electricity = qty;
						fiveDosingSchedule.CarStatus = CarSatusDic[(CarStatus)carEle.CarStatus];
						fiveDosingSchedule.TongXinPath = carEle.TongXin ? AGVCarStatus.TongXinOK : AGVCarStatus.TongXinError;
					}

					TongXinTimeDic[carEle.CarNumber] = DateTime.Now;
					AppRuntime.GetService().GetService<AgvCarService>().UpdateAGVElEQty(new AgvCar { CarNumber = carEle.CarNumber, Electricity = carEle.Qty, CarStatus = (CarStatus)carEle.CarStatus });

				}
			}

			if(topic== "UpdateCarStatus")
			{
				InitAGV();
			}


			return Task.CompletedTask;
		}

		public void RabbitHandler(object? model, BasicDeliverEventArgs args)
		{

			//A0200402-0000-0000-0000-000000000000:23.4795
			var body = args.Body.ToArray();
			var message = Encoding.UTF8.GetString(body);
			if (!string.IsNullOrWhiteSpace(message) && message.IndexOf(":") > 0)
			{
				var arrays = message.Split(":");
				var cageId = arrays[0];
				decimal.TryParse(arrays[1], out var cage_temp);
				if (cage_temp > AppRuntime.MaxTemperature || cage_temp < AppRuntime.MinTemperature)
				{
					StartAlarm();
				}
			}

			Console.WriteLine($" [x] Received {message}");
		}

		public void StartAlarm()
		{
			ShowAlarmGif = AlarmGif[1];
			AlarmHelper.StartAlarm();
		}


		private string[] AlarmGif = new string[] { "Hidden", "Visible" };
		public LsdViewModel()
		{
			ShowAlarmGif = AlarmGif[0];
			Sensor_temperature_All = 20;
			Sensor_humidity_All = 5;
			Sensor_co2_All = 5;

			ShuiLian_All = 5;
			DaoLiuBan_All = 5;
			DianDongBaiYe_All = 5;
			DaFengJiZu_All = 25;
			CePaiFeng_All = 30;
			XinFeng_All = 5;

			SelectModelTextA = ModelTextArray[0];
			SelectModelTextB = ModelTextArray[1];
			SelectModelTextC = ModelTextArray[2];
			SelectModelTextD = ModelTextArray[3];
			SelectModelTextE = ModelTextArray[0];
			InitQMitsubishiPlc();
			InitGeLongJianKong();
			InitAGV();
			InitChart();

			InitRightTopPanel();

			InitDevice();

			InitTimer();
			InitRabbitMQ();


		}

		public void InitHuKong()
		{
			CurrentTemperature = PLCDic["A"].室外温度探头() / 10;
		}

		private void InitGeLongJianKong()
		{
			var areaName = "";
			var dto = AppRuntime.GetService().GetService<PigeonCageService>().GetPigeCageDtoProce(areaName);

			GeLongGuanLi = dto.GeLongGuanLi;
			JianKangJianCha = dto.JiangKangJianCha;
			ChaDan = dto.ChaDan;
			ZhaoDan = dto.ZhaoDan;
			ChaChu = dto.ChaChu;
			ChuLan = dto.ChuLan;
			TaoTai = dto.TaoTai;
			TiaoBing = dto.TiaoBing;
			BuLan = dto.BuLan;
			KongZhigeLong = dto.KongZhigeLong;

		}
		private void InitAGV()
		{
			var avcars = AppRuntime.GetService().GetService<AgvCarService>().GetAgvCarList();
			var schedules = AppRuntime.GetService().GetService<DosingScheduleService>().GetDosingScheduleList();
			var vms = new List<DosingScheduleViewModel>();
			for (int i = 0; i < avcars.Count; i++)
			{
				var info = schedules.FirstOrDefault(x => x.CarId == avcars[i].ID);
				var tt = new DosingScheduleViewModel();
				if (info != null)
				{
					tt.Electricity = (int)(avcars[i].Electricity / avcars[i].MaxElectricQty.Value * 100);
					tt.ID = info.ID;
					tt.CarId = info.CarId;
					tt.HourFirst = info.HourFirst;
					tt.HourSecond = info.HourSecond;
					tt.HourThird = info.HourThird;
					tt.CarStatus = CarSatusDic[avcars[i].CarStatus];
					tt.MinuteFirst = info.MinuteFirst;
					tt.MinuteSecond = info.MinuteSecond;
					tt.MinuteThird = info.MinuteThird;

					tt.First_80 = info.First_80;
					tt.First_120 = info.First_120;
					tt.First_160 = info.First_160;
					tt.First_200 = info.First_200;
					tt.Second_80 = info.Second_80;
					tt.Second_120 = info.Second_120;
					tt.Second_160 = info.Second_160;
					tt.Second_200 = info.Second_200;
					tt.Third_80 = info.Third_80;
					tt.Third_120 = info.Third_120;
					tt.Third_160 = info.Third_160;
					tt.Third_200 = info.Third_200;
					if (TongXinTimeDic.ContainsKey(avcars[i].CarNumber))
					{
						TongXinTimeDic[avcars[i].CarNumber] = DateTime.Now;
					}
					else
					{
						TongXinTimeDic.Add(avcars[i].CarNumber, DateTime.Now);
						tt.TongXinPath = AGVCarStatus.TongXinOK;
					}
					
					
					vms.Add(tt);
				}

			}
			

			FirstDosingSchedule = vms[0];
			SecondDosingSchedule = vms[1];
			ThirdDosingSchedule = vms[2];
			FourDosingSchedule = vms[3];
			FiveDosingSchedule = vms[4];
		}

		
		private void InitChart()
		{
			TemperatureList.Clear();
			HumidityList.Clear();
			Co2List.Clear();
			for (int i = 0; i < 5; i++)
			{
				var tt = Random.Shared.Next(30, 45);
				TemperatureList.Add(tt);
				var tt_0 = Random.Shared.Next(30, 50);
				HumidityList.Add(tt_0);
				var tt_1 = Random.Shared.Next(100, 300);
				Co2List.Add(tt_1);
			}

		}


		private void UpdateChart()
		{
			//获取温度
			var temperature_List = new List<decimal>();
			var temperature_OK = new List<int>();
			var temperature_out = new List<decimal>();
			var co2_List = new List<decimal>();
			var co2_OK = new List<int>();
			for (int i = 0; i < AreaList.Length; i++)
			{
				try
				{
					var temperature_i = PLCDic[AreaList[i]].GetAvageTemperature();
					temperature_List.Add(temperature_i.temperature_in);
					temperature_OK.Add(temperature_i.OK);
					temperature_out.Add(temperature_i.temperature_out);
				}
				catch (Exception ex)
				{
					temperature_List.Add(25);
					AppRuntime.Logger_Error(ex);
				}
				try
				{
					var co2 = PLCDic[AreaList[i]].二氧化碳探头();
					co2_List.Add(co2);
					co2_OK.Add(1);
				}
				catch (Exception ex)
				{
					co2_List.Add(0);
					AppRuntime.Logger_Error(ex);
				}

			}

			TemperatureList.Clear();
			//HumidityList.Clear();
			Co2List.Clear();
			for (int i = 0; i < AreaList.Length; i++)
			{
				TemperatureList.Add(temperature_List[i]);
				Co2List.Add(co2_List[i]);
			}

			CurrentTemperature = temperature_out.Average();
			Sensor_temperature_Use = temperature_OK.Sum();
			Sensor_co2_Use = co2_OK.Sum();


		}


		private void UpdateHuanKong()
		{

			var lst = new List<HuanKongModel>();

			for (int i = 0; i < AreaList.Length; i++)
			{
				try
				{
					var res = PLCDic[AreaList[i]].GetHuanKong();
					lst.Add(res);
				}
				catch (Exception ex)
				{
					AppRuntime.Logger_Error(ex);
				}
			}

			ShuiLian_Use = lst.Sum(x => x.ShuiLian_OK);
			ShuiLian_Error = lst.Sum(x => x.ShuiLian_Error);

			DaoLiuBan_Use = lst.Sum(x => x.DaoLiuBan_OK);
			DaoLiuBan_Error = lst.Sum(x => x.DaoLiuBan_Error);

			DianDongBaiYe_Use = lst.Sum(x => x.BaiYeChuang_OK);
			DianDongBaiYe_Error = lst.Sum(x => x.BaiYeChuang_Error);

			DaFengJiZu_Use = lst.Sum(x => x.DaFengJiZu_OK);
			DaFengJiZu_Error = lst.Sum(x => x.DaFengJiZu_Error);

			CePaiFeng_Use = lst.Sum(x => x.CePaiFeng_OK);
			CePaiFeng_Error = lst.Sum(x => x.CePaiFeng_Error);

			XinFeng_Use = lst.Sum(x => x.XinFeng_OK);
			XinFeng_Error = lst.Sum(x => x.XinFeng_Error);

		}
		private void InitRightTopPanel()
		{
			var now = DateTime.Now;
			CurrentDate = now.ToString("yyyy-MM-dd");
			CurrentTime = now.ToString("HH:mm:ss");
			CurrentWeek = WeekChinese[(int)now.DayOfWeek];
			CurrentTemperature = 33;
		}

		//private Dictionary<string, QMitsubishiPlc> PLCDic = new Dictionary<string, QMitsubishiPlc>();
		//private Dictionary<string, ModBusTcp> PLCDic = new Dictionary<string, ModBusTcp>();

		private Dictionary<string, ModbusRtuOverTcpPlc> PLCDic = new Dictionary<string, ModbusRtuOverTcpPlc>();
		private void InitQMitsubishiPlc()
		{
			var equips = AppRuntime.GetService().GetService<DeviceManagerService>().GetDosingEquipmentList();
			if (equips == null || equips.Count <= 0) return;
			for (int i = 0; i < equips.Count; i++)
			{
				if (string.IsNullOrWhiteSpace(equips[i].Ip)) continue;
				if (equips[i].Port <= 0) continue;
				if (string.IsNullOrWhiteSpace(equips[i].Region)) continue;
				try
				{
					//var tt = new QMitsubishiPlc(equips[i].Ip, equips[i].Port, MitsubishiVersion.Qna_3E);
					var tt = new ModbusRtuOverTcpPlc(equips[i].Ip, equips[i].Port);
					PLCDic.Add(equips[i].Region, tt);

				}
				catch (Exception ex)
				{
					Growl.ErrorGlobal(new GrowlInfo
					{
						Message = ex.Message,
						WaitTime = 6,
						IsCustom = true,
					});
					AppRuntime.Logger_Error(ex);
				}

			}

		}


		#region  定时器
		private Timer second_Timer;
		private Timer minute_Timer;
		private Timer minute_10_Timer;

		private void InitTimer()
		{
			second_Timer = new Timer(SecondTimerHandle, null, 1000, 1000);
			minute_Timer = new Timer(MinuteTimerHandle, null, 1000 * 60, 1000 * 60);
			minute_10_Timer = new Timer(Minute10TimerHandle, null, 1000 * 60 * 10, 1000 * 60 * 10);



		}

		public void CheckCarTongXin()
		{
			foreach (var item in TongXinTimeDic)
			{
				var time = (DateTime.Now - item.Value).TotalSeconds;
				if (time > 180)
				{
					if (item.Key == "A" || item.Key == "1") firstDosingSchedule.TongXinPath = AGVCarStatus.TongXinError;
					else if (item.Key == "B" || item.Key == "2") secondDosingSchedule.TongXinPath = AGVCarStatus.TongXinError;
					else if (item.Key == "C" || item.Key == "3") thirdDosingSchedule.TongXinPath = AGVCarStatus.TongXinError;
					else if (item.Key == "D" || item.Key == "4") fourDosingSchedule.TongXinPath = AGVCarStatus.TongXinError;
					else if (item.Key == "E" || item.Key == "5") fiveDosingSchedule.TongXinPath = AGVCarStatus.TongXinError;
				}
			}
		}
		private void SecondTimerHandle(object args)
		{
			try
			{
				InitRightTopPanel();
				CheckCarTongXin();

			}
			catch (Exception ex)
			{
				AppRuntime.Logger_Error(ex);
			}

		}
		private void MinuteTimerHandle(object args)
		{
			try
			{
				InitChart();
				InitAGV();
				InitHuKong();
			}
			catch (Exception ex)
			{

				AppRuntime.Logger_Error(ex);

			}
		}
		private void Minute10TimerHandle(object args)
		{
			try
			{
				InitGeLongJianKong();
			}
			catch (Exception ex)
			{

				AppRuntime.Logger_Error(ex);

			}

		}
		#endregion
		
		[RelayCommand]
		public async Task ShowPropertyWindow(string areaName)
		{

			var propertyWindow = new MainWindow();
			if (propertyWindow.DataContext is MainWindowViewModel temp)
			{
				temp.AreaName = areaName;
				temp.InitData();
			}
			if (propertyWindow.homepage.DataContext is HomePageViewModel homePageViewModel)
			{
				homePageViewModel.Region = areaName;
				homePageViewModel.InitData();
			}
			if (propertyWindow.parameterSetting.DataContext is ParameterSettingViewModel parameterSetting)
			{
				parameterSetting.Region = areaName;
				parameterSetting.InitData();
			}
			if (propertyWindow.deviceManager.DataContext is DeviceManagerViewModel deviceManagerViewModel)
			{
				deviceManagerViewModel.Region = areaName;
				deviceManagerViewModel.InitData();
			}
			if (propertyWindow.agvCarPage.DataContext is AGVCarPageViewModel agvCarPageViewModel)
			{
				agvCarPageViewModel.Region = areaName;
				agvCarPageViewModel.InitData();
			}
			AppRuntime.Logger_Info("双击进入属性页面");
			propertyWindow.ShowDialog();
		}

		private string GetDeviceTemperatureModel(decimal temperature, DosingParameter parameter)
		{
			if (temperature >= parameter.AlarmTemperature) return "报警温度";
			else if (temperature >= parameter.CoolingTemperature) return "降温模式";
			else if (temperature >= parameter.KeepTemperature) return "保温模式";
			return "适宜温度";

		}
		public void InitDevice()
		{
			var devices = AppRuntime.GetService().GetService<DeviceManagerService>().GetDosingEquipmentList();
			var paramters = AppRuntime.GetService().GetService<ParameterSettingService>().GetDosingParameters();
			if (devices.Count <= 0) return;
			var firstparam = paramters.FirstOrDefault(x => x.Region == "A");
			if (firstparam == null) return;
			AlarmTemperature = firstparam.AlarmTemperature;
			UpperTemperature_ShuiLian = firstparam.StartTemperatureWaterPump;
			StartTime_ShuiLian = firstparam.StopTimeWaterPump;

			devices.ForEach(x =>
			{
				var paramter = paramters.FirstOrDefault(m => m.Region == x.Region) ?? new QModels.DosingParameter();
				switch (x.Region)
				{
					case "A":
						{
							SelectModelTextA = ModelTextArray[x.SeasonalPattern];
							AreaModel_A = GetDeviceTemperatureModel(Temperature_A, paramter);
							DangWei_A = "1";
							RunTime_A = "00:00";
							Auto_Temperature_A = paramter.SuitableTemperature;
							break;
						}
					case "B":
						{

							SelectModelTextB = ModelTextArray[x.SeasonalPattern];
							AreaModel_B = GetDeviceTemperatureModel(Temperature_B, paramter);
							RunTime_B = "00:00";
							DangWei_B = "1";
							Auto_Temperature_B = paramter.SuitableTemperature;

							break;
						}
					case "C":
						{
							SelectModelTextC = ModelTextArray[x.SeasonalPattern];
							AreaModel_C = GetDeviceTemperatureModel(Temperature_C, paramter);
							RunTime_C = "00:00";
							DangWei_C = "1";
							Auto_Temperature_C = paramter.SuitableTemperature;

							break;
						}

					case "D":
						{
							SelectModelTextD = ModelTextArray[x.SeasonalPattern];
							AreaModel_D = GetDeviceTemperatureModel(Temperature_D, paramter);
							RunTime_D = "00:00";
							DangWei_D = "1";
							Auto_Temperature_D = paramter.SuitableTemperature;
							break;
						}

					case "E":
						{
							SelectModelTextE = ModelTextArray[x.SeasonalPattern];
							AreaModel_E = GetDeviceTemperatureModel(Temperature_E, paramter);
							RunTime_E = "00:00";
							DangWei_E = "1";
							Auto_Temperature_E = paramter.SuitableTemperature;

							break;
						}
					default:
						break;
				}

			});

		}


		[RelayCommand]
		public void ClearAlarm()
		{
			ShowAlarmGif = AlarmGif[0];
			AlarmHelper.StopAlarm();
		}

		[RelayCommand]
		public void LookCageTemperatureError()
		{

		}










	}


}
